package com.xiangxiangjd.config.springsecurity;

import com.alibaba.fastjson.JSONObject;
import com.xiangxiangjd.config.token.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * Spring security登录成功处理类,返回jwt
 *  * GYB
 *  * 20190220
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");

        //从authentication中获取用户信息
        final JwtUser userDetail = (JwtUser) authentication.getPrincipal();


        //生成jwt
        String token =  jwtUtils.createJwt(userDetail.getUsername(),"",new HashMap<>());

        httpServletResponse.addHeader("token", "Bearer " + token);
        JSONObject map = new JSONObject();
        map.put("code", "200");
        map.put("message", "登录成功");
        map.put("data","Bearer " + token);

        httpServletResponse.getWriter().write(map.toString());


        httpServletResponse.getWriter().flush();
    }
}
